/**
 * Currency Converter
 * SSUI Assignment 2
 * 
 * Team Members: Victor Rivera
 * 				 Tiffany Ng
 * 			     Justine Yang
 * 			     Syp Vandy
 */

package com.android.converter;

import java.text.DecimalFormat;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This class holds methods to populate and display widgets in order to 
 * perform a currency conversion.
 * 
 */
public class CurrencyConverter extends Activity {
	
	//Necessary widgets
	//Source and Target currencies
	Spinner spinnerSource;
    Spinner spinnerTarget;
    
    //We need to obtain/update information from these Widgets:  
	Button button;		// button to listen for onClick   
    EditText amount;	// Amount to convert
    TextView value;		// Widget to display the answer
    
    double[] values;	// array to store values from DB
	
	private ConverterDbAdapter theadapter;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        initWidgets();
    }
    
    /**
     * This method initializes widgets (except for spinners) from main.xml
     */
    public void initWidgets(){
    	//Spinner
    	dataSpinnerFromDB();
    	
    	button = (Button) this.findViewById(R.id.converter);
    	button.setWidth(130); 
        button.setOnClickListener(myListener);
        
        amount = (EditText) this.findViewById(R.id.amount);
        value = (TextView) this.findViewById(R.id.value);
    	
    }
    
    /**
     * This method populates the spinners using the data from the DB.
     */
    void dataSpinnerFromDB(){
    	theadapter = new ConverterDbAdapter(this);
     	theadapter.open();
     	//theadapter.fillData();
     	
     	Cursor thecursor = theadapter.fetchAllCurrencies();
        startManagingCursor(thecursor);
 
        //Access the DB to get the respective value
        int v = thecursor.getCount();
        values = new double[v];
        if (thecursor.moveToFirst()) {
        	int i = 0; 
            int nameColumn = thecursor.getColumnIndex("value"); 
            do {
                // Get the field values
                values[i] = Double.parseDouble(thecursor.getString(nameColumn));
               i++;
            } while (thecursor.moveToNext());

        }
        thecursor.moveToFirst();
        spinnerSource = (Spinner) findViewById(R.id.sourceS);
        spinnerTarget = (Spinner) findViewById(R.id.targetS);
        
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
        	    android.R.layout.simple_spinner_item, // Use a template
        	                                          // that displays a
        	                                          // text view
        	    thecursor, // Give the cursor to the list adapter
        	    new String[] {"currency"}, // Map the NAME column in the
        	                                         // people database to...
        	    new int[] {android.R.id.text1}); // The "text1" view defined in
        	                                     // the XML template
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
         
        //Set the values to each spinner. 
        spinnerSource.setAdapter(adapter);
        spinnerTarget.setAdapter(adapter);
    }
    
    /**
     * This method listens for when the user clicks on the "Convert" button. 
     */
    private OnClickListener myListener = new OnClickListener() {
    	public void onClick(View v){
    		String amountValue = amount.getText().toString();
    		String result1 = "0";
    		if (!amountValue.equals("")){
    			double vamount = Double.parseDouble(amountValue);
	    		int vsource = spinnerSource.getSelectedItemPosition();
	    		int vtarget = spinnerTarget.getSelectedItemPosition();
	    		
	    		
	    		DecimalFormat twoDForm = new DecimalFormat("#.00");
	    		double result = converter(vsource,vtarget,vamount);
	    		//result = Double.valueOf(twoDForm.format(result));
	    		result1 = twoDForm.format(result);
    		}else{
    			displayMessageBox("Empty field.");
    		}
	    	value.setText(result1);
	    		
        }
    };
    
    /**
     * This method displays a message (used for blank input).
     * 
     * @param message - the message to display
     */
    public void displayMessageBox(String message){
        Toast t = Toast.makeText(this,message,Toast.LENGTH_SHORT);
        t.setMargin(t.getHorizontalMargin(), 400);
        t.show();
    }
  
    /**
     * This method calculates the converted amount.
     * 
     * @param source - the value in Euros of 1 denomination in the source currency
     * @param target - the value in Euros of 1 denomination in the target currency
     * @param amount - the converted amount from source to target currency
     * @return double - the converted value
     */
    public double converter(int source, int target, double amount ){
    	return (amount * values[source])/values[target];
    }
}